package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTaskActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProTaskDetailActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.MissonInfo;
import com.linkage.jz.bankruptcy.bean.CommonStatusInfo;
import com.linkage.jz.bankruptcy.bean.UserInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.linkage.jz.bankruptcy.utils.Utils.StringToLeng;

/**
 * @author FT
 * @time 2016-07-18 16:49
 */

// JUMP 
public class ProZQSetFragment extends Fragment {
    RecyclerView mRecyclerView;
    private Context context;
    private int mPage;
    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";
    private DemoAdapter mAdapter;
    private static String infoid;
    private LinearLayout ll_addTalk;
    List<MissonInfo> mData;

    public static ProZQSetFragment newInstance(int page, String infoid) {
        Bundle args = new Bundle();
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        args.putString("infoid", infoid);
        ProZQSetFragment tripFragment = new ProZQSetFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPage = getArguments().getInt(MERCHANT_DETAILS_PAGE);
        infoid = getArguments().getString("infoid");
        context = getActivity().getApplicationContext();
//        setData();
        mData = new ArrayList<MissonInfo>();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_detailpro_zq_set, container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView);
        ll_addTalk = (LinearLayout)view.findViewById(R.id.ll_addTalk);
        ll_addTalk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CreateProTaskActivity.class);
                intent.putExtra(BaseActivity.KEY_PROJECTID, infoid);
                startActivity(intent);
            }
        });

        initAdapter(mData);
        getData();
        return view;
    }

    private void setData(){
//        mFoodData = new ArrayList<>();
//        for(int i=0; i<5;i++){
//            mFoodData.add("美食"+i);
//        }

    }
    /**
     * 设置RecyclerView属性
     */
    private void initAdapter(List<MissonInfo> data) {
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new DemoAdapter(getActivity(), R.layout.fragment_pro_detailpro_zq_set_item, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);//设置adapter
        //设置item点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()) {

                    case R.id.ll_taskitem:

//                        ProTalkDetailActivity msgDetailActivity = new ProTalkDetailActivity();

                        Intent intent = new Intent(getActivity(), ProTaskDetailActivity.class);
                        startActivity(intent);
                        break;

                }
            }
        });


    }
    /**
     * adapter
     */
    class DemoAdapter extends BaseQuickAdapter<MissonInfo, BaseViewHolder> {
        int mLayoutId;
        public DemoAdapter(Context context, int LayoutId, List<MissonInfo> str) {
            super( LayoutId, str);
            mLayoutId = LayoutId;
        }

        @Override
        public void convert(BaseViewHolder helper, MissonInfo info) {

            helper.addOnClickListener(R.id.ll_taskitem);
            helper.setText(R.id.tv_tasktitle,info.getTaskName());

            UserInfo userInfo = info.getExecutor();
            if(userInfo!=null) {
                helper.setText(R.id.tv_settinger, "执行人："+userInfo.getUsername());
            }
            userInfo = info.getCreator();
            if(userInfo!=null) {

                helper.setText(R.id.tv_creater, "创建人："+userInfo.getUsername());
            }


            long date = StringToLeng(info.getFinishTime())*1000;
            String strTime = Utils.timeStamp2Date(date, "yyyy-MM-dd HH:mm:ss");
            helper.setText(R.id.tv_tasktime,"截止时间："+strTime);

            CommonStatusInfo taskStatusInfo = info.getStatus();
            if(taskStatusInfo !=null) {
                if("2".equalsIgnoreCase(taskStatusInfo.getValue()))
                {
                    helper.setTextColor(R.id.tv_taskstatus,getResources().getColor(R.color.page_top));
                }else{
                    helper.setTextColor(R.id.tv_taskstatus,getResources().getColor(R.color.red));
                }
                helper.setText(R.id.tv_taskstatus,  taskStatusInfo.getText());
            }

        }
    }

    public void getData()
    {

        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {

            return;
        }
//        ll_nodata.setVisibility(View.GONE);
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("userToken", userToken)
                .add("token", BankruptcyApp.tokeninfo.getToken())
//                .add("token", "")

                .add("pageNumber","1")
                .add("pageSize","100")
                .add("projectId",infoid)
                .add("isManager","1")

                .build();

        String url = Consts.WEBURL_TASKLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                String str = response.body().string();
//                if(Consts.ISDEBUG)
//                {
                str = "{\"code\":0,\"msg\":\"system.success\",\"data\":{\"createPermission\":true,\"taskList\":{\"list\": [{\n" +
                        "\"id\": \"ec26d67883dc4698bd5bcbd9c47675c2\",\n" +
                        "\"bankruptcyProjectId\": \"9c208e41eab641d59b88372c986605e9\",\n" +
                        "\"taskName\": \"任务名称20190408\",\n" +
                        "\"taskContent\": \"任务内容20190408\",\n" +
                        "\"memberId\": \"c32c1f4fafe9424485d54ae14ac7cab9\",\n" +
                        "\"deadlineTime\": 1552355250,\n" +
                        "\"status\": {\n" +
                        "\"value\": 2,\n" +
                        "\"text\": \"已完成\"\n" +
                        "},\n" +
                        "\"finishTime\": 1554707246,\n" +
                        "\"feedbackMessage\": \"测试通知消息\",\n" +
                        "\"executor\": {\n" +
                        "\"id\": \"c32c1f4fafe9424485d54ae14ac7cab9\",\n" +
                        "\"loginname\": \"18655452308\",\n" +
                        "\"username\": \"18655452308\",\n" +
                        "\"avatar\": null,\n" +
                        "\"company\": null,\n" +
                        "\"userOnline\": true,\n" +
                        "\"disabled\": false,\n" +
                        "\"email\": null,\n" +
                        "\"mobile\": \"18655452308\",\n" +
                        "\"loginAt\": 1554775592,\n" +
                        "\"loginIp\": \"127.0.0.1\",\n" +
                        "\"loginCount\": 3,\n" +
                        "\"loginSessionId\": \"311iiiv9f2j5po1eo1qbr09j0n\",\n" +
                        "\"customMenu\": null,\n" +
                        "\"loginTheme\": null,\n" +
                        "\"menuTheme\": null,\n" +
                        "\"loginSidebar\": false,\n" +
                        "\"loginBoxed\": false,\n" +
                        "\"loginScroll\": false,\n" +
                        "\"loginPjax\": true,\n" +
                        "\"appInfoIdAndroid\": \"6748524783374e008f1103ea819a0fda\",\n" +
                        "\"appInfoIdIos\": null,\n" +
                        "\"unitid\": \"4db0951b9c5c4bbfbf6cf104cc2511c0\",\n" +
                        "\"unit\": null,\n" +
                        "\"appInfoIos\": null,\n" +
                        "\"appInfoAndroid\": null,\n" +
                        "\"roles\": null,\n" +
                        "\"units\": null,\n" +
                        "\"menus\": null,\n" +
                        "\"firstMenus\": null,\n" +
                        "\"secondMenus\": null,\n" +
                        "\"customMenus\": null,\n" +
                        "\"qq\": null,\n" +
                        "\"wx\": null,\n" +
                        "\"opBy\": \"\",\n" +
                        "\"opAt\": 1552445670,\n" +
                        "\"delFlag\": false\n" +
                        "},\n" +
                        "\"creator\": {\n" +
                        "\"id\": \"93bec345da1d4699b2782c44bf190faf\",\n" +
                        "\"loginname\": \"18655752308\",\n" +
                        "\"username\": \"王富贵\",\n" +
                        "\"avatar\": \"group1/M00/00/04/rBHd5Fya1PmACFKoAAA7GwNBo1Q524.jpg\",\n" +
                        "\"company\": \"江苏萌发科技有限公司\",\n" +
                        "\"userOnline\": true,\n" +
                        "\"disabled\": false,\n" +
                        "\"email\": \"1262333517@qq.com\",\n" +
                        "\"mobile\": \"18655752308\",\n" +
                        "\"loginAt\": 1555291645,\n" +
                        "\"loginIp\": \"127.0.0.1\",\n" +
                        "\"loginCount\": 42,\n" +
                        "\"loginSessionId\": \"rshheaodbogbpo222899cl973s\",\n" +
                        "\"customMenu\": null,\n" +
                        "\"loginTheme\": \"palette.2.css\",\n" +
                        "\"menuTheme\": null,\n" +
                        "\"loginSidebar\": false,\n" +
                        "\"loginBoxed\": false,\n" +
                        "\"loginScroll\": true,\n" +
                        "\"loginPjax\": false,\n" +
                        "\"appInfoIdAndroid\": \"6748524783374e008f1103ea819a0fda\",\n" +
                        "\"appInfoIdIos\": null,\n" +
                        "\"unitid\": \"4db0951b9c5c4bbfbf6cf104cc2511c0\",\n" +
                        "\"unit\": null,\n" +
                        "\"appInfoIos\": null,\n" +
                        "\"appInfoAndroid\": null,\n" +
                        "\"roles\": null,\n" +
                        "\"units\": null,\n" +
                        "\"menus\": null,\n" +
                        "\"firstMenus\": null,\n" +
                        "\"secondMenus\": null,\n" +
                        "\"customMenus\": null,\n" +
                        "\"qq\": null,\n" +
                        "\"wx\": null,\n" +
                        "\"opBy\": \"93bec345da1d4699b2782c44bf190faf\",\n" +
                        "\"opAt\": 1551945057,\n" +
                        "\"delFlag\": false\n" +
                        "},\n" +
                        "\"opBy\": \"93bec345da1d4699b2782c44bf190faf\",\n" +
                        "\"opAt\": 1554706728,\n" +
                        "\"delFlag\": false\n" +
                        "}],\"localArrayList\":[1],\"totalCount\":0,\"pageSize\":100,\"pageNo\":1,\"minPage\":1,\"maxPage\":1,\"totalPage\":1}}}";
//                }
                try{
                    JSONObject object = new JSONObject(str);
                    JSONObject jsondata = object.getJSONObject("data");
                    JSONObject jsontaskList = jsondata.getJSONObject("taskList");
                    Gson gson = new Gson();
                    MissonInfo[] array = new Gson().fromJson(jsontaskList.optString("list"),MissonInfo[].class);
                    List<MissonInfo> list = Arrays.asList(array);
//                        BankruptcyApp.tokeninfo = info;
                    mData.clear();
                    mData.addAll(list);

                    if(mData.size()>0)
                    {

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                ll_nodata.setVisibility(View.GONE);
//                                mDataRv.setVisibility(View.VISIBLE);
                            }

                        });
                    }else{
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                ll_nodata.setVisibility(View.VISIBLE);
//                                mDataRv.setVisibility(View.GONE);
                            }

                        });
                    }
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            mAdapter.notifyDataSetChanged();

                        }

                    });

                }catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }


}
